﻿using JJYChengTaskWinForm.Enums;
using JJYChengTaskWinForm.Factory.Test;
using JJYChengTaskWinForm.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace JJYChengTaskWinForm
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        private void MainForm_Load(object sender, EventArgs e)
        {

            TestEnum.TestRun();
            runLogTextBox.ScrollBars = ScrollBars.Vertical;
            errorLogTextBox.ScrollBars = ScrollBars.Vertical;
            filePathTextBox.Text = "C:\\JJYChengTaskFiledb\\";
            // Todo:绑定任务
            List<KeyValueModel> comboBoxData = new List<KeyValueModel>() {
            new KeyValueModel(){Key = "SqlServer测试",Value = "SqlServerTest"},
            new KeyValueModel(){Key = "MySql测试",Value = "MySqlTest"},
            new KeyValueModel(){Key = "测试任务3",Value = "Test3"}
            };
            comboBox1.Items.Clear();
            comboBox1.DataSource = comboBoxData;
            comboBox1.DisplayMember = "Key";      // 显示字段
            comboBox1.ValueMember = "Value";        // 值字段
            comboBox1.SelectedValue = "MySqlTest"; // 绑定默认选项
        }
        private int timeNumber = 0;
        private bool IsTimeNumber = true;
        private  void  button1_Click(object sender, EventArgs e)
        {
            IsTimeNumber = true;
            timeNumber = 0;
            // 获取选中的对象（KeyValueModel）
            var selectedItem = (KeyValueModel)(comboBox1.SelectedItem ?? new KeyValueModel());

            // 获取 Key 和 Value
            string selectedKey = selectedItem.Key;
            string selectedValue = selectedItem.Value;

            if (string.IsNullOrWhiteSpace(filePathTextBox.Text))
            {
                MessageBox.Show("请选择文件存放路径", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                button1.Enabled = false;
                 Task.Run(async () =>
                {

                    // Todo: 执行你的任务
                    switch (selectedValue)
                    {
                        case "SqlServerTest":
                            TimeNumberRun();
                            await SqlServerTest.Run(this, filePathTextBox.Text);
                            break;
                        case "MySqlTest":
                            TimeNumberRun();
                            await MySqlTest.Run(this, filePathTextBox.Text);
                            break;
                        default:
                            MessageBox.Show("未找到任务", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            break;
                    }
                    CompletedAction();//执行完成


                });
            }
        }

        #region  窗体业务（不需要修改）
        private void textBox1_Click(object sender, EventArgs e)
        {

            // 可选：设置对话框标题
            folderBrowserDialog1.Description = "请选择一个文件夹";

            // 可选：设置起始路径（例如桌面）
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Desktop;

            // 可选：设置是否显示新文件夹按钮
            folderBrowserDialog1.ShowNewFolderButton = true;

            // 显示对话框并获取用户选择结果
            DialogResult result = folderBrowserDialog1.ShowDialog();

            if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(folderBrowserDialog1.SelectedPath))
            {
                filePathTextBox.Text = folderBrowserDialog1.SelectedPath;
            }

        }
        private void TimeNumberRun()
        {
            Task.Run(() =>
            {
                while (IsTimeNumber)
                {
                    SetButton1Text();
                    timeNumber++;
                    Thread.Sleep(1000);
                }
            });
        }

        private delegate void Button1Delegate();
        private void SetButton1Text()
        {
            Button1Delegate button1Delegate = delegate ()
            {
                button1.Text = $"执行中...（{timeNumber}）";
            };
            button1.Invoke(button1Delegate);
        }
        private delegate void RunLogTextDelegate();
        public void SetRunLogText(string val)
        {
            RunLogTextDelegate runLogTextDelegate = delegate ()
            {
                runLogTextBox.AppendText($" \r\n [{DateTime.Now}] {val}");
                runLogTextBox.SelectionStart = runLogTextBox.Text.Length;
                runLogTextBox.ScrollToCaret();
            };
            runLogTextBox.Invoke(runLogTextDelegate);
        }
        private delegate void ErrorLogTextDelegate();
        public void SetRrrorLogText(string val)
        {
            ErrorLogTextDelegate errorLogTextDelegate = delegate ()
            {
                errorLogTextBox.AppendText($" \r\n [{DateTime.Now}] {val}");
                errorLogTextBox.SelectionStart = errorLogTextBox.Text.Length;
                errorLogTextBox.ScrollToCaret();
            };
            runLogTextBox.Invoke(errorLogTextDelegate);
        }

        private delegate void CompletedDelegate();
        /// <summary>
        /// 完成
        /// </summary>
        /// <param name="val"></param>
        public void CompletedAction()
        {
            CompletedDelegate completedDelegate = delegate ()
            {
                button1.Enabled = true;
                button1.Text = "开始执行";
                IsTimeNumber = false;
            };
            button1.Invoke(completedDelegate);
        }
        #endregion


    }
}
